import smap.archiver.client
import time
import scipy.interpolate
import csv
import calendar
from datetime import datetime
from dateutil import tz

#change the name and location of the output file
f1 = open('/home/cbe/.gvfs/bsg on 169.229.130.74/SIMULATIONS/PROJECTS/NYT_CPB_Calib model/Analysis/DH/cart_test2.csv', 'wb')
testsout = csv.writer(f1,dialect='excel') 

#input stream ids
c = smap.archiver.client.SmapClient(base='http://new.openbms.org/backend', key='SA2nYWuHrJxmPNK96pdLKhnSSYQSPdALkvnA', private=True)

#insert time zone and local time (local to project time zone)
#takes a time, adds project time zone to it, converts to utc time tuple and then to utc seconds since epoch for smap
dt_format = '%Y-%m-%d %H:%M:%S'
time_zone = tz.gettz('EST5EDT')
start_time = int(calendar.timegm(datetime.strptime('2011-09-14 09:30:00', dt_format).replace(tzinfo=time_zone).utctimetuple()))
end_time = int(calendar.timegm(datetime.strptime('2011-09-15 09:30:00', dt_format).replace(tzinfo=time_zone).utctimetuple()))
newdata = c.data('Metadata/Extra/DeviceName = \'Cart\'',start_time, end_time)
data = []
for row in newdata[1]:
    times = row[:,0]
    timea = []
    for time in times:
        timea.append(datetime.fromtimestamp(time/1000, time_zone).strftime(dt_format))
    values = row[:,1]
    data.append(timea)
    data.append(values)
transposed = zip(*data)

headings = []
for x in xrange(len(newdata[0])):
    uuid = newdata[0][x]
    headings.append('uuid')
    headings.append(uuid)
testsout.writerow(headings)
headings = []
for x in xrange(len(newdata[0])):
    uuid = newdata[0][x]
    headings.append('name')
    headings.append(c.query('select distinct Metadata/Extra/SensorLocation where uuid = \'%s\'' % uuid))
testsout.writerow(headings)
    

for row in transposed:
    testsout.writerow(row)

f1.close()


